import {
    AfterViewInit,
    Component,
    Injector,
    Input,
    OnChanges,
    OnDestroy,
    OnInit,
    Renderer2,
    SimpleChanges,
    ViewChild
} from '@angular/core';
import { ConfigModule } from 'src/app/config.module';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { NzModalRef, NzModalService } from 'ng-zorro-antd/modal';
import { DragDrop } from '@angular/cdk/drag-drop';
import { NgxPermissionsService } from 'ngx-permissions';
import { DictDataModel } from '../../model/dictTypeModel';
import { DictDataService } from '../../service/dict-data.service';
import { NzMessageService } from 'ng-zorro-antd/message';
import { styleDict } from '../../../../../common/dicData';

@Component({
    selector: 'app-dict-data-option',
    templateUrl: './dict-data-option.component.html',
    styleUrls: ['./dict-data-option.component.scss']
})
export class DictDataOptionComponent implements OnInit, AfterViewInit, OnDestroy, OnChanges {
    @ViewChild('modalContent') modalContent;
    @ViewChild('modalFooter') modalFooter;
    @Input() tableComponent: any;
    @Input()
    dictTypeId: string;
    modalLoadingState: boolean;
    saveLoadingState: boolean;
    dataForm: FormGroup;
    dictDataModel: DictDataModel = {} as DictDataModel;
    modalRef: NzModalRef; //操作弹窗
    constructor(
        public _config: ConfigModule,
        private _formBuilder: FormBuilder,
        private _router: Router,
        private _activatedRoute: ActivatedRoute,
        private _nzModalService: NzModalService,
        private _renderer2: Renderer2,
        private _dragDrop: DragDrop,
        private _ngxPermissionsService: NgxPermissionsService,
        private _injector: Injector,
        private dictDataService: DictDataService,
        private msg: NzMessageService
    ) {
        // 表单验证
        this.dataForm = this._formBuilder.group({
            dictLabel: ['', [Validators.required]],
            dictValue: ['', [Validators.required]],
            cssClass: [''],
            dictSort: ['',Validators.required],
            listClass: [''],
            remark: [''],
        });
    }

    ngOnChanges(changes: SimpleChanges): void {
    }

    ngOnInit() {
    }

    ngAfterViewInit() {}

    ngOnDestroy() {
    }


    onModalOpen(id: string, cateId: string) {
        this.dictDataModel.dictCode = id;
        this.dictDataModel.dictType = cateId;
        this.modalRef = this._nzModalService.create({
            nzTitle: id ? '编辑字典项' : '新增字典项',
            nzContent: this.modalContent,
            nzFooter: this.modalFooter,
            nzWidth: this._config.modalWidth,
            nzBodyStyle: this._config.modalContentHeight,
        });

        this.modalRef.afterOpen.subscribe(() => {
            const modalDragRef = this._renderer2.selectRootElement('.ant-modal-content', true);
            const modalDragHeaderRef = this._renderer2.selectRootElement('.ant-modal-header', true);

            const modalDrag = this._dragDrop.createDrag(modalDragRef);
            modalDrag.withHandles([modalDragHeaderRef]);
            modalDrag.withBoundaryElement(document.body);
        });

        this.modalRef.afterClose.subscribe(() => {
            this.dataForm.reset();
            for (const key of Object.keys(this.dictDataModel)) {
                delete this.dictDataModel[key];
            }
        });

        //编辑时先获取详情
        if (id) {
            this.modalLoadingState = true;
            this.dictDataService.get(id).subscribe((res) => {
                if (res.success) {
                    this.dictDataModel = res.data;
                }
            }).add(()=>this.modalLoadingState = false);
        }
    }

    /**
     * 保存
     */
    onSave() {
        if (this.dictDataModel.dictCode) {
            this.dictDataService.update(this.dictDataModel).subscribe((res) => {
                if (res.success) {
                    this.modalRef.close();
                    this.dataForm.reset();
                    this.msg.success(res.msg);
                    //改变子组件的refresh属性
                    this.tableComponent.tableData.forEach(item => {
                        if (item.dictType === this.dictDataModel.dictType){
                            item.refresh = Math.random();
                        }
                    });

                    //清除模态框数据
                    for (const key of Object.keys(this.dictDataModel)) {
                        delete this.dictDataModel[key];
                    }
                }
            });
        } else {
            this.dictDataService.add(this.dictDataModel).subscribe((res) => {
                if (res.success) {
                    this.modalRef.close();
                    this.dataForm.reset();
                    this.msg.success(res.msg);
                    //改变子组件的refresh属性
                    this.tableComponent.tableData.forEach(item => {
                        if (item.dictType === this.dictDataModel.dictType){
                            item.refresh = Math.random();
                        }
                    });

                    //清除模态框数据
                    for (const key of Object.keys(this.dictDataModel)) {
                        delete this.dictDataModel[key];
                    }
                }
            });
        }
    }

    info(itemElement: any): void {
    }

    protected readonly styleDict = styleDict;
}
